package com.aidong.pay.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.drawCode.biz.DrawBiz;
import com.aidong.drawCode.entity.DrawCode;
import com.aidong.jobs.async.SmsTask;
import com.aidong.login.biz.MemberIntegralLogBiz;
import com.aidong.login.entity.MemberIntegralLog;
import com.aidong.pay.biz.MsmAppointmentToRemindBiz;
import com.aidong.pay.biz.OrderManagementBiz;
import com.aidong.pay.biz.OrdergeneratedBiz;
import com.aidong.pay.config.util.AlipayNotify;
import com.aidong.pay.config.util.ClenderUtil;
import com.aidong.pay.entity.Recommend;
import com.aidong.util.IntegralAction;
import com.aidong.util.RandomUtil;

@ParentPackage("json")
@Namespace("/")
public class AlipayReturnAction {
	private OrdergeneratedBiz ordergeneratedBiz;

	private MsmAppointmentToRemindBiz appointmentToRemindBiz;

	private OrderManagementBiz orderManagementBiz;

	private MemberIntegralLogBiz logBiz;
	
	@Autowired
	private DrawBiz drawBiz;
	

	private String out_trade_no = ""; // 商务订单号

	private String trade_no = ""; // 交易流水号

	private String trade_status = ""; // 交易状态

	private String gmt_payment = ""; // 交易付款时间

	@Autowired
	public void setOrdergeneratedBiz(OrdergeneratedBiz ordergeneratedBiz) {
		this.ordergeneratedBiz = ordergeneratedBiz;
	}

	public void setOut_trade_no(String out_trade_no) {
		this.out_trade_no = out_trade_no;
	}

	public void setTrade_no(String trade_no) {
		this.trade_no = trade_no;
	}

	@Autowired
	public void setAppointmentToRemindBiz(MsmAppointmentToRemindBiz appointmentToRemindBiz) {
		this.appointmentToRemindBiz = appointmentToRemindBiz;
	}

	@Autowired
	public void setOrderManagementBiz(OrderManagementBiz orderManagementBiz) {
		this.orderManagementBiz = orderManagementBiz;
	}

	@Autowired
	public void setLogBiz(MemberIntegralLogBiz logBiz) {
		this.logBiz = logBiz;
	}

	@Autowired
	SmsTask smsTask;

	public void setTrade_status(String trade_status) {
		this.trade_status = trade_status;
	}

	public void setGmt_payment(String gmt_payment) {
		this.gmt_payment = gmt_payment;
	}

	/**
	 * 支付宝异步通知
	 * 
	 * @return
	 */
	@Action(value = "alipayreturn")
	public String alipayReturnMethod() {
		Map<String, String> params = AlipayNotify.getAlipayInfo();
		System.err.println("支付宝回调--------" + params);
		boolean isSign = AlipayNotify.verify(params);
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (isSign) { // 验证成功
			if (trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED")) {
				// 回调记录
				Map<String, Object> backMap = new HashMap<String, Object>();
				try {
					backMap.put("orderId", Integer.valueOf(params.get("out_trade_no")));

					backMap.put("backTime", gmt_payment);
					backMap.put("backType", 1);
					backMap.put("buyerUserId", params.get("buyer_email"));
					backMap.put("totalAmount", Double.parseDouble(params.get("total_fee")));
					backMap.put("tradeNo", params.get("trade_no"));
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					orderManagementBiz.addPayCallBack(backMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				int orderId = Integer.valueOf(out_trade_no);
				Map<String, Object> disposeMap = ordergeneratedBiz.getPayOrderDispose(orderId);
				int applyFlg = Integer.valueOf(disposeMap.get("applyFlg").toString()); // 同步处理状态
				int orderType = Integer.valueOf(disposeMap.get("orderType").toString()); // 订单类型
				int subscribeId = Integer.valueOf(disposeMap.get("subscribeId").toString()); // 预约号
				String recommendCoach = null;
				if (disposeMap.get("recommendCoach") != null)
					recommendCoach = disposeMap.get("recommendCoach").toString();
				/**
				 * 获取和金额有关
				 */
				double totalFee = 0.00;
				double actually = 0.00;
				try {
					totalFee = Double.parseDouble(params.get("total_fee"));// 金额
					actually = Double.parseDouble(disposeMap.get("actually").toString());// 实付金额
				} catch (Exception e) {
				}

				DecimalFormat df = new DecimalFormat("#0.00");
				System.out.println("支付宝支付金额：" + df.format(actually) + "商品实付金额：" + df.format(totalFee));
				if (df.format(actually).equals(df.format(totalFee))) {
					// 根据订单号 查询使用人的爱动号
					Map<String, Object> paraMap1 = new HashMap<String, Object>();
					paraMap1.put("orderId", orderId);
					Map<String, Object> statuMap = orderManagementBiz.getOrderBackStatus(paraMap1);
					int idongId = Integer.valueOf(statuMap.get("idongId").toString());
					int status = Integer.valueOf(statuMap.get("status").toString());
					// 修改兑换券或代金券表-此处无法判断使用的是代金券还是兑换券，故一起更新实际上会被更新的也只有一个
					// 查询券表 与成功的ID是否一致
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("orderId", orderId);
					paraMap.put("idongId", idongId);

					String tickNo = "";

					if (applyFlg == 0) {
						Map<String, Object> memberMap = ordergeneratedBiz.getPayMemberPhone(orderId);
						tickNo = ClenderUtil.electronicTicketNo(memberMap.get("phoneNo").toString()); // 电子券号
						// payTime = gmt_payment;
					}
					// 修改订单信息
					if (status == 0) {
						Map<String, Object> orderMap = new HashMap<String, Object>();
						orderMap.put("tickNo", tickNo);
						orderMap.put("orderId", orderId);
						orderMap.put("tradeNo", trade_no);
						orderMap.put("payType", 1);
						orderMap.put("payTime", gmt_payment);
						orderMap.put("status", 1);
						orderMap.put("processId", 2);
						orderManagementBiz.editOrderPayInfo(orderMap);

						// 修改预约状态
						Map<String, Object> subMap = new HashMap<String, Object>();
						subMap.put("applyType", orderType);
						subMap.put("subscribeId", subscribeId);
						subMap.put("status", 0);
						try {
							//orderManagementBiz.editAppointStatus(subMap);
							orderManagementBiz.editAppointCampaignStatus(subMap);
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
						// 修改代金券一类
						orderManagementBiz.editCouponsInfo(paraMap);
						orderManagementBiz.editExchangeTicketsInfo(paraMap);

					}

					if (applyFlg == 0 && status == 0) { // 同步未处理
						
						if(orderType!=1){
							int cou=drawBiz.getDrawCountByNowTime(new Date());
							if(cou>0){
								//为新用户生成码
								DrawCode code=new DrawCode();
								code.setIdongId(idongId);
								code.setCode(RandomUtil.randDrawCode(4));
								if(orderType == 2){
									code.setBak("课程");
								}else if(orderType == 3){
									code.setBak("营养品");
								}else if(orderType == 4){
									code.setBak("健康餐");
								}else if(orderType == 5){
									code.setBak("装备");
								}else{
									code.setBak("未知");
								}
								drawBiz.addDrawCode(code);
							}
						}
						
						// 预约短信通知
						if (orderType == 1) { // 活动
							Map<String, Object> activityTypeMap = ordergeneratedBiz.getActivityType(orderId);
							int moviceFlag = Integer.valueOf(activityTypeMap.get("movieFlg").toString());

							Map<String, Object> mstMap = appointmentToRemindBiz.addCampaginRemind(orderId);
							String cellNumber = mstMap.get("phoneNo").toString(); // 电话号码
							String title = mstMap.get("title").toString(); // 活动标题
							String subscribeActiveId = mstMap.get("subscribeId").toString(); // 预约ID
							String date = mstMap.get("startTime").toString(); // 活动开始时间
							String address = mstMap.get("place").toString(); // 活动地点
							String voucherNo = mstMap.get("tickNo").toString(); // 券号
							if (moviceFlag == 0) {
								/*
								 * SMSUtil.pool.execute(new Runnable() { public
								 * void run() {
								 */
								try {
									// 手机号码后四位
									String latFourPhone = voucherNo.substring(voucherNo.length() - 4,
											voucherNo.length());
									// 电子券号前八位
									String topEight = voucherNo.substring(0, 8);
									// 短信提醒
									smsTask.activityRemind(cellNumber, title, subscribeActiveId, date, address,
											topEight, latFourPhone);
								} catch (Exception e) {
									e.printStackTrace();
								}
								/*
								 * } });
								 */
							} else if (moviceFlag == 1) {
								// 根据订单ID查收电影券信息
							}

						} else if (orderType == 2) { // 课程
							Map<String, Object> courseMap = appointmentToRemindBiz.addCourseRemind(orderId);
							String cellNumber = courseMap.get("phoneNo").toString(); // 电话号码
							String subscribeCourseId = courseMap.get("subscribeId").toString(); // 预约ID
							String courseName = courseMap.get("coureName").toString(); // 课程名
							String date = courseMap.get("subscribeDate").toString(); // 上课日期
							String time = courseMap.get("startTime").toString(); // 上课时间
							String dateTime = date + " " + time; // 上课开始时间
							String storeName = courseMap.get("storeName").toString(); // 场馆名
							String voucherNo = courseMap.get("tickNo").toString(); // 券号
							/*
							 * SMSUtil.pool.execute(new Runnable() { public void
							 * run() {
							 */
							try {
								// 手机号码后四位
								String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
								// 电子券号前八位
								String topEight = voucherNo.substring(0, 8);
								// 短信提醒
								smsTask.courseAppointment(cellNumber, subscribeCourseId, courseName, dateTime,
										storeName, topEight, latFourPhone);
							} catch (Exception e) {
								e.printStackTrace();
							}
							/*
							 * } });
							 */
						} else if (orderType == 3 || orderType == 4 || orderType == 5) { // 健康餐饮
							Map<String, Object> foodMap = appointmentToRemindBiz.addFoodBuyRemind(orderId);
							String phoneNo = foodMap.get("phoneNo").toString(); // 电话号码
							String quantity = foodMap.get("quantity").toString(); // 数量
							String foodName = foodMap.get("foodName").toString(); // 餐名
							String buyDate = foodMap.get("buyDate").toString(); // 预订日期
							String pickUpForm = foodMap.get("pickUpForm").toString(); // 取餐开始日期
							String pickUpTo = foodMap.get("pickUpTo").toString(); // 取餐截止如期
							String pickDate = buyDate + " " + pickUpForm + "-" + pickUpTo;
							String storeName = foodMap.get("storeName").toString(); // 门店
							String voucherNo = foodMap.get("tickNo").toString(); // 电子券号
							String pickUpWay = foodMap.get("pickUpWay").toString(); // 取货方式
							/*
							 * SMSUtil.pool.execute(new Runnable() { public void
							 * run() {
							 */
							try {
								// 手机号码后四位
								String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
								// 电子券号前八位
								String topEight = voucherNo.substring(0, 8);
								// 短信提醒
								if ("2".equals(pickUpWay)) {
									smsTask.foodAppointmentT(phoneNo, quantity, foodName);
								} else {
									smsTask.foodAppointment(phoneNo, quantity, foodName, pickDate, storeName, topEight,
											latFourPhone);
								}

							} catch (Exception e) {
								e.printStackTrace();
							}
							/*
							 * } });
							 */
						}
					}
					try {
						// 推荐返点计算
						if (!StringUtils.isBlank(recommendCoach)) {
							Recommend recommend = orderManagementBiz.getRecommendInfo(out_trade_no);
							if (recommend != null && recommend.getRecommendIdongId() != 0
									&& recommend.getRecommendAmount() != 0) {
								logBiz.addLog(new MemberIntegralLog(recommend.getRecommendIdongId(),
										IntegralAction.order.getActionValue(),
										(new Double(recommend.getRecommendAmount())).intValue(),
										"订单号-" + out_trade_no));
							}
						}
					} catch (Exception e) {
					}
					out.println("success"); // 请不要修改或删除
				}
			}
		} else {// 验证失败
			out.println("fail");
		}
		return null;
	}
}
